import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
// import { getLocalStorage } from '@/utils/storage';
// import  UserState from "@/store/modules/user";

import store from '@/store';
import router from '@/router';

function handlePath(path) {
  const paths = ['governance', 'report', 'template'];
  const newPath = path.split('/');

  // 不能进行跳转，未升级正式版，存在权限限制
  if (newPath.length === 3 && !paths.includes(newPath[2])) {
    return false;
  }
  // 可以进行跳转
  return true;
}

NProgress.configure({ showSpinner: false });
const whiteListRouters = store.getters['permission/whiteListRouters'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const token = store.getters['user/token'];
  if (token) {
    if (to.path === '/login') {
      setTimeout(() => {
        store.dispatch('user/logout');
        store.dispatch('permission/restore');
      });
      next();
      return false;
    }
    // ToDo
    // handlePath(to.path)
    if (handlePath(to.path)) {
      // next({ ...to });
      // return
    }

    // 拿到角色权限
    const roles = store.getters['user/roles'];
    if (roles && roles.length > 0) {
      next();
    } else {
      try {
        await store.dispatch('user/getUserInfo');
        // 初始化，拿到用户权限，发请求
        await store.dispatch('permission/initRoutes', store.getters['user/roles']);

        next({ ...to });
      } catch (error) {
        await store.commit('user/removeToken');
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    /* white list router */
    if (whiteListRouters.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
    NProgress.done();
  }
});

router.afterEach(() => {
  NProgress.done();
});
